import React, { useEffect, useMemo, useState } from 'react'
import axios from 'axios'
import {
  NavBar,
  Button,
  Space,
  Grid,
  Card,
  Tag,
  Skeleton,
  ErrorBlock,
  Empty,
  ActionSheet,
  DotLoading,
  Popup,
} from 'antd-mobile'
import { AppstoreOutline, CloseOutline } from 'antd-mobile-icons'
import BackToTop from '../../components/BackToTop'
import { useNavigate } from 'react-router-dom'

// 数据类型
export type TrainingItem = {
  id: number
  title: string
  level: '零基础' | '初学者' | '进阶'
  duration: string
  cover: string
}

const FILTERS = ['全部训练', '零基础', '初学者', '进阶'] as const
export type Filter = typeof FILTERS[number]

const Training: React.FC = () => {
  const [filter, setFilter] = useState<Filter>('全部训练')
  const [list, setList] = useState<TrainingItem[]>([])
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [sheetVisible, setSheetVisible] = useState(false)
  const [popupVisible, setPopupVisible] = useState(false)
  const [useAdvanced, setUseAdvanced] = useState(false)
  // 高级筛选面板状态
  const [advCategory, setAdvCategory] = useState<string | null>(null)
  const [advPrice, setAdvPrice] = useState<string | null>(null)
  const [advLevel, setAdvLevel] = useState<'零基础' | '初学者' | '进阶' | '强化' | null>(null)
  const [advDuration, setAdvDuration] = useState<string | null>(null)
  const [advEquipment, setAdvEquipment] = useState<string | null>(null)

  const actions = useMemo(
    () =>
      FILTERS.map((f) => ({
        text: f,
        key: f,
        onClick: () => {
          setFilter(f)
          setSheetVisible(false)
        },
      })),
    []
  )

  const minutesFrom = (duration: string) => {
    const m = String(duration || '').match(/(\d+)/)
    return m ? parseInt(m[1], 10) : NaN
  }

  const fetchData = async (current: Filter) => {
    try {
      setError(null)
      setLoading(true)
      // 使用 Vite 代理到本地 JSON 服务，解决在手机上访问时 localhost 指向手机自身的问题
      const url = '/api/trainings'
      const params = current === '全部训练' ? {} : { level: current }
      const { data } = await axios.get<TrainingItem[]>(url, { params })
      // 后端直接返回来自 MySQL trainings 表的数据，其中 cover 字段即为图片地址
      setList(data || [])
    } catch (e: any) {
      setError(e?.message || '加载失败')
      setList([])
    } finally {
      setLoading(false)
    }
  }

  // 高级筛选请求：后端按 level 过滤，前端按时长区间二次过滤
  const fetchByAdvanced = async () => {
    try {
      setError(null)
      setLoading(true)
      const url = '/api/trainings'
      const levelParam = advLevel && ['零基础', '初学者', '进阶'].includes(advLevel) ? advLevel : undefined
      const { data } = await axios.get<TrainingItem[]>(url, { params: levelParam ? { level: levelParam } : {} })

      let result = (data || []) as TrainingItem[]
      // 时长区间过滤
      if (advDuration) {
        const ranges: Record<string, [number, number]> = {
          '15–20 min': [15, 20],
          '20–30 min': [20, 30],
          '30–40 min': [30, 40],
        }
        const [min, max] = ranges[advDuration] || [0, 1000]
        result = result.filter((it) => {
          const m = minutesFrom(it.duration)
          return !isNaN(m) && m >= min && m <= max
        })
      }

      // 分类/器材 以标题关键词模拟过滤（后端无字段）
      if (advCategory) {
        result = result.filter((it) => it.title.includes(advCategory as string))
      }
      if (advEquipment) {
        result = result.filter((it) => it.title.includes(advEquipment as string))
      }

      const withCovers = result.map((it, idx) => ({
        ...it,
        cover:
          it?.cover && String(it.cover).trim().length > 0
            ? it.cover
            : `https://picsum.photos/seed/training-${it?.id ?? idx + 1}/400/300`,
      }))
      setList(withCovers)

      // 同步顶部级别激活状态
      if (levelParam) {
        setFilter(levelParam as Filter)
      } else {
        setFilter('全部训练')
      }
    } catch (e: any) {
      setError(e?.message || '加载失败')
      setList([])
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    if (useAdvanced) return
    fetchData(filter)
  }, [filter, useAdvanced])
const nav  = useNavigate()
  const mytraining = () => {
    nav('/mytraining')
  }

  return (
    <div className="training-page">
      <NavBar
        backArrow={null}
        left={<span onClick={mytraining} className="nb-title">训练</span>}
        right={
          <Button size="mini" color="primary" fill="solid" onClick={() => setPopupVisible(true)}>
            <AppstoreOutline />
          </Button>
        }
      />

      <div className="training-filters">
        <Space wrap>
          {FILTERS.map((f) => (
            <Button
              key={f}
              size="small"
              shape="rounded"
              color="primary"
              fill={f === filter ? 'solid' : 'outline'}
              onClick={() => { setUseAdvanced(false); setFilter(f) }}
            >
              {f}
            </Button>
          ))}
        </Space>
      </div>

      {loading && (
        <div className="training-loading">
          <Skeleton.Title animated />
          <Skeleton.Paragraph lineCount={1} animated />
          <div style={{ height: 8 }} />
          <Grid columns={2} gap={8}>
            {Array.from({ length: 6 }).map((_, i) => (
              <Skeleton animated key={i} />
            ))}
          </Grid>
          <div className="loading-inline">
            <DotLoading /> 正在加载…
          </div>
        </div>
      )}

      {!loading && error && (
        <ErrorBlock status="default" title="加载失败" description={error} />
      )}

      {!loading && !error && (
        <>
        

          {list.length === 0 ? (
            <Empty description="暂无数据" />
          ) : (
            <Grid columns={2} gap={8} className="training-grid">
              {list.map((item) => (
                <Grid.Item key={item.id}>
                  <Card className="training-card" title={item.title}>
                    <div className="training-cover-wrap">
                      <img
                        alt={item.title}
                        src={item.cover}
                        className="training-cover"
                        onError={(e) => {
                          (e.currentTarget as HTMLImageElement).src = `https://picsum.photos/seed/training-${item.id}/400/300`
                        }}
                      />
                    </div>
                    <div className="training-meta">
                      <Tag color="primary" fill="light">
                        {item.level}
                      </Tag>
                      <span className="training-duration">{item.duration}</span>
                    </div>
                  </Card>
                </Grid.Item>
              ))}
            </Grid>
          )}
        </>
      )}

      <ActionSheet
        visible={sheetVisible}
        actions={actions}
        cancelText="取消"
        onClose={() => setSheetVisible(false)}
      />

      {/* 高级筛选弹层 */}
      <Popup visible={popupVisible} onMaskClick={() => setPopupVisible(false)} bodyStyle={{ borderTopLeftRadius: 12, borderTopRightRadius: 12 }}>
        <div className="filter-popup">
          <div className="fp-header">
            <span className="fp-title">筛选</span>
            <span className="fp-close" onClick={() => setPopupVisible(false)}><CloseOutline /></span>
          </div>

          <div className="fp-section">
            <div className="section-title">分类</div>
            <Space wrap>
              {['力量训练', '瑜伽', '跳绳', '拳击', '跑步', '塑形', '动感单车'].map((t) => (
                <Button key={t} size="small" shape="rounded" className={`chip ${advCategory === t ? 'active' : ''}`} onClick={() => setAdvCategory(advCategory === t ? null : t)}>
                  {t}
                </Button>
              ))}
            </Space>
          </div>

          <div className="fp-section">
            <div className="section-title">价格</div>
            <Space wrap>
              {['免费', '增值'].map((t) => (
                <Button key={t} size="small" shape="rounded" className={`chip ${advPrice === t ? 'active' : ''}`} onClick={() => setAdvPrice(advPrice === t ? null : t)}>
                  {t}
                </Button>
              ))}
            </Space>
          </div>

          <div className="fp-section">
            <div className="section-title">级别</div>
            <Space wrap>
              {['零基础', '初学者', '进阶', '强化'].map((t) => (
                <Button key={t} size="small" shape="rounded" className={`chip ${advLevel === t ? 'active' : ''}`} onClick={() => setAdvLevel(advLevel === t ? null : (t as any))}>
                  {t}
                </Button>
              ))}
            </Space>
          </div>

          <div className="fp-section">
            <div className="section-title">时长</div>
            <Space wrap>
              {['15–20 min', '20–30 min', '30–40 min'].map((t) => (
                <Button key={t} size="small" shape="rounded" className={`chip ${advDuration === t ? 'active' : ''}`} onClick={() => setAdvDuration(advDuration === t ? null : t)}>
                  {t}
                </Button>
              ))}
            </Space>
          </div>

          <div className="fp-section">
            <div className="section-title">器材</div>
            <Space wrap>
              {['瑜伽垫', '弹力带', '泡沫轴'].map((t) => (
                <Button key={t} size="small" shape="rounded" className={`chip ${advEquipment === t ? 'active' : ''}`} onClick={() => setAdvEquipment(advEquipment === t ? null : t)}>
                  {t}
                </Button>
              ))}
            </Space>
          </div>

          <div className="fp-footer">
            <Button fill="none" onClick={() => { setAdvCategory(null); setAdvPrice(null); setAdvLevel(null); setAdvDuration(null); setAdvEquipment(null); }}>重置</Button>
            <Button fill="solid" color="default" style={{ background: 'rgb(229, 80, 26)', borderColor: 'rgb(229, 80, 26)', color: '#fff' }} onClick={() => { setUseAdvanced(true); fetchByAdvanced(); setPopupVisible(false) }}>提交</Button>
          </div>
        </div>
      </Popup>

      {/* 局部样式，按图示还原 */}
      <style>{`
        .training-page { padding: 16px; --adm-color-primary: rgb(229, 80, 26); }
        .training-filters { margin: 12px 0; }
        .training-banner-wrap { margin-bottom: 10px; }
        .training-banner { position: relative; width: 100%; height: 110px; border-radius: 12px; background: linear-gradient(135deg, #ffd6cc, #ffe6e1); overflow: hidden; padding: 12px; box-sizing: border-box; }
        .training-banner-text { font-weight: 700; font-size: 14px; color: #333; line-height: 1.4; max-width: 60%; }
        .training-banner-img { position: absolute; right: 6px; bottom: 0; height: 100%; object-fit: cover; }
        .training-grid { margin-top: 8px; }
        .training-card { --adm-card-border-radius: 10px; --adm-color-background: #fff; overflow: hidden; }
        .training-cover { width: 100%; height: 100px; object-fit: cover; }
        .training-meta { display: flex; align-items: center; justify-content: space-between; margin-top: 8px; color: #6b6b6b; font-size: 12px; }
        .training-duration { color: #999; }
        .nb-title { font-weight: 700; font-size: 20px; color: #111; }
        .training-loading { padding: 8px 0; }
        .loading-inline { margin-top: 12px; display: flex; align-items: center; gap: 6px; color: #888; font-size: 13px; justify-content: center; }

        /* 弹层样式 */
        .filter-popup { padding: 16px; max-height: 80vh; overflow: auto; }
        .fp-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px; }
        .fp-title { font-weight: 700; font-size: 18px; }
        .fp-close { font-size: 18px; }
        .fp-section { margin-top: 14px; }
        .section-title { color: #222; font-weight: 600; margin-bottom: 10px; }
        .chip { border-color: rgb(229, 80, 26); color: rgb(229, 80, 26); }
        .chip.active { background: rgb(229, 80, 26); color: #fff; }
        .fp-footer { position: sticky; bottom: 0; background: #fff; display: flex; justify-content: space-between; gap: 12px; padding-top: 12px; }
        .fp-footer .adm-button { flex: 1; height: 40px; border-radius: 999px; }
      `}</style>

      <BackToTop bgColor="rgb(229, 80, 26)" size={44} threshold={240} />
   </div>
  )
}

export default Training
